import { useMutation } from "react-relay";
import {useCallback, useState} from "react";
import { RecordSourceSelectorProxy, } from "relay-runtime";
import {useToast} from "customize-easy-ui-component";
const graphql = require("babel-plugin-relay/macro");

const mutation = graphql`
  mutation useFillEqpFieldMutation($detId: ID!) {
    reportFillEqpField(detId: $detId){
     id snapshot
    }
  }
`;

export default function useFillEqpFieldMutation() {
  //返回简单结果字段
  const [result, setResult] =useState<string>('');
  const [commit, doing] = useMutation(mutation);
  const toast = useToast();
  return {
    call:useCallback(
      (detId: string) => {
        return commit({
          variables: {
            detId,
          },
          updater: (store: RecordSourceSelectorProxy) => {
            const payload = store.getRootField("reportFillEqpField");
            if (!payload) {
              return;
            }
            //这里无法获取整个Mutation的应答结果，只能够获取字段，所以很多要再套一层结构{task,changeByUserId}好处理获取整个task。或是返回null表示失败？
            const ret = payload.getValue("snapshot") as string;
            setResult(ret as string);
           toast({
              title: "后端应答",
              subtitle: ret,
              intent: "info"
            });
          },
          onError: error => {
            toast({title: "后端回答",subtitle: ""+error, intent: "warning"});
          }
        });
      },
      [commit,toast]
    ),
    doing,
    result
  };
}
